'use strict'

let { User, questionnaires, problem, score, isokQuestionnaireUsers } = require('../models');
const auth = require('../utils/auth')

let index_fn = async (ctx, next) => {
    let username = ctx.session.userName;
    let userIds = [];
    let quests = JSON.parse(JSON.stringify(await questionnaires.findAll({
        order: [
            ['id', 'desc']
        ]
    })));
    let id = [];
    let remarks = [];
    let Name = [];
    let fromUserId = [];
    quests.forEach(item => {
        id.push(item.id);
        userIds.push(item.fromUserId);
        remarks.push(item.remarks);
        Name.push(item.Name);
        fromUserId.push(item.fromUserId)
    });
    let obj = {
        quests,
        username
    }

    ctx.render('index.html', obj)
}


let login_fn = async (ctx, next) => {
    console.log(ctx.path);
    ctx.render('login.html')
}

let register_fn = async (ctx, next) => {
    ctx.render('register.html')
}

let loginDone_fn = async (ctx, next) => {
    let uid = ctx.request.body.username || ' ';
    let pwd = ctx.request.body.password || ' ';
    let res = '';
    if (uid.length > 0 && pwd.length > 0) {
        let row = await User.findOne({
            where: {
                username: uid,
                password: pwd
            }
        });
        let users = JSON.stringify(row);
        console.log(users);
        if (users !== 'null') {
            ctx.session.userId = row.id;
            console.log(row.id);
            ctx.session.userName = row.username;
            console.log(row.username);
            res = { code: 200, msg: '登录成功' }
        }
        else {
            res = { code: 1000, msg: '抱歉，账号或密码错误' }
        }

    }
    else {
        res = { code: 1000, msg: '抱歉，账号或密码不能为空' }
    };
    ctx.body = JSON.stringify(res);
}
let registerDone_fn = async (ctx, next) => {
    let uid = ctx.request.body.username.trim() || '';
    let pwd = ctx.request.body.password.trim() || '';
    let confirmpwd = ctx.request.body.confirmpassword.trim() || '';

    let res = '';
    if (uid.length > 0 && pwd.length > 0 && pwd === confirmpwd) {
        let row = await User.findOne({
            where: {
                username: uid
            }
        });
        let u2Json = JSON.stringify(row);
        if (u2Json === 'null') {
            let u1 = await User.create({
                username: uid,
                password: pwd
            });
            let u1Json = JSON.stringify(u1);
            if (u1Json !== 'null') {
                res = { code: 200, msg: '用户注册成功' };
            } else {
                res = { code: 1000, msg: '因为服务器或者网络原因，用户未注册成功' };
            }
        } else {
            res = { code: 1000, msg: '当前用户名已经注册，请确认后重试' };
        }
    } else {
        res = { code: 1000, msg: '用户名和密码不能为空，且两密码应该一致' };
    }
    ctx.body = JSON.stringify(res);
};

let newQuestionnaire_fn = async (ctx, next) => {
    ctx.render('newQuestionnaire.html')
}

let questionnaireDone_fn = async (ctx, next) => {

    //获取该问卷id，以便使用
    let res = ' ';
    let qutid1 = ctx.request.body.index;
    ctx.session.qutid = qutid1;
    console.log(ctx.session.qutid + "该问卷id");
    res = { code: 200, msg: '成功' };
    ctx.body = JSON.stringify(res);
}

//根据获得的问卷id，进入到该问卷，并获取该问卷的基本信息传入前端questionnaire，以便前端使用
let questionnaire_fn = async (ctx, next) => {
    let qutid = ctx.session.qutid;
    console.log(qutid + "aaa");
    //查询所有问卷id为qutid的问题，并根据id排序
    let p1 = JSON.parse(JSON.stringify(await problem.findAll({
        where: {
            questionnaireId: qutid
        },
        order: [
            ['id']
        ]
    })));
    let q1 = JSON.parse(JSON.stringify(await questionnaires.findOne({
        where: {
            id: qutid
        }
    })))
    console.log(p1);
    //打包封装
    if (p1 !== 'null') {
        let obj = {
            p1,
            q1
        }
        obj.p1.forEach((item, index) => {
            item.myid = index + 1;
        })
        ctx.render('questionnaire.html', obj)
    }

    else {
        console.log(失败);
    }

}

let logout_fn = async (ctx, next) => {
    ctx.session = null;
    ctx.body = { code: 200, msg: '注销成功' };
}

//建立问卷页面
let createQuestionnaire_fn = async (ctx, next) => {

    //获取问卷的信息
    let titleName = ctx.request.body[0].value || ' ';
    let Remarks1 = ctx.request.body[1].value || ' ';
    let userId = ctx.session.userId;
    // //建立问卷
    if (titleName !== ' ' && Remarks1 !== ' ') {
        let q1 = await questionnaires.create({
            fromUserId: userId,
            Name: titleName,
            remarks: Remarks1
        });

        let oparr = []

        for (let i = 2; i < ctx.request.body.length; i++) {
            oparr.push({
                questionnaireId: q1.getDataValue('id'),
                content: ctx.request.body[i].value
            })
        }
        console.log(oparr);
        console.log(ctx.request.body.length);
        let isnullOrNot = oparr.every(item => item.content.trim().length > 0);
        if (isnullOrNot == true) {
            let obj = await problem.bulkCreate(oparr)

            let reuslt = JSON.parse(JSON.stringify(obj))

            console.log(reuslt);
            if (reuslt !== 'null') {
                ctx.body = { code: 200, reuslt, msg: '创建成功' }
            }
            else {
                ctx.body = { code: 1000, msg: '问题创建失败' }
            }
        }

        else {
            ctx.body = { code: 1003, msg: '抱歉，问题不能为空，你可以选择删除不要的问题栏' }
        }
    }
    else {
        ctx.body = { code: 1002, msg: '问卷名及备注不能为空' }
    }

}

let information_fn = async (ctx, next) => {
    let username = ctx.session.userName;
    console.log(username);
    let obj = {
        username
    }
    ctx.render('information.html', obj)
}

let addScoreDone_fn = async (ctx, next) => {
    let rq = ctx.request.body;
    let uid = ctx.session.userId;
    let arrScore = [];
    let qid = ctx.session.qutid;
    //查询表isokQuestionnaireUsers中的用户id跟问卷id，判断该用户是否已填写该问卷
    let isokQuestUser = await isokQuestionnaireUsers.findOne({
        where: {
            UserId: uid,
            QuestionnnaireId: qid
        }
    })

    console.log('判断为空');
    //如果为空，则未填写
    if (!isokQuestUser) {
        console.log('我进来了');
        for (let i = 0; i < rq.score.length; i++) {
            arrScore.push({
                problemId: rq.problem[i],
                score: rq.score[i],
                fromUserId: uid
            })
        }

        console.log(arrScore, 'score');


        let obj = await score.bulkCreate(arrScore);

        if (obj) {
            await isokQuestionnaireUsers.create({
                QuestionnnaireId: qid,
                UserId: uid
            });
            ctx.body = { code: 200, msg: '建立成功' };
        }
        else {
            ctx.body = { code: 1000, msg: '编辑失败' }
        }
    }
    //相反，则未填写，允许填写
    else {
        ctx.body = { code: 1000, msg: '编辑失败，该问卷你已回答' }
    }

}


//更改密码
let updatePasswordDone_fn = async (ctx, next) => {
    let pwd = ctx.request.body.password;
    let name = ctx.request.body.username;
    let newPwd = ctx.request.body.newpassword;
    let conPwd = ctx.request.body.confirmPassword;
    console.log(ctx.request.body);
    if (pwd.length > 0 && name.length > 0 && newPwd.length > 0 && conPwd.length > 0 && conPwd === newPwd) {
        let conUser = await User.findOne({
            where: {
                username: name,
                password: pwd
            }
        })
        if (conUser !== 'null') {
            let newUser = await User.update({
                username: name,
                password: newPwd,

            }, {
                where: {
                    username: name,
                    password: pwd
                }
            });
            if (newUser !== 'null') {
                ctx.body = { code: 200, msg: '修改成功' }
            }
        }
        else {
            ctx.body = { code: 1000, msg: '抱歉，账号或密码错误，且两次密码需要一致且不为空' }
        }
    }
    else {
        ctx.body = {
            code: 1000, msg: '抱歉，账号或密码不能为空'
        }
    }



}

let updatePassword_fn = async (ctx, next) => {
    ctx.render('updatePwd.html')
}
// let addScore_fn = async (ctx, next) => {
//     ctx.render('index.html');
// }

let myQuestionnaire_fn = async (ctx, next) => {

    let uid = ctx.session.userId;
    //获取自身用户已填写问卷
    let myQut = await isokQuestionnaireUsers.findAll({
        where: {
            UserId: uid
        }
    })
    let myq1 = JSON.parse(JSON.stringify(myQut))
    //根据已填写问卷id来获得问卷详细信息
    let myqId = [];
    myq1.forEach(item => {
        myqId.push(item.QuestionnnaireId);
    })

    console.log(myqId);
    let myAllQut = await questionnaires.findAll({
        where: {
            id: myqId
        }
    })
    let myAllQut1 = JSON.parse(JSON.stringify(myAllQut))
    console.log(myAllQut1);
    //根据问卷id来获取问题id，再根据问题id来获取分数
    let obj = {
        myAllQut1,
    }

    ctx.render('myQuestionnaire.html', obj)

}

let myQuestionnaireDone_fn = async (ctx, next) => {
    ctx.body = {
        code: 200,
        msg: '成功'
    }
}

let fillingStatusDone_fn = async (ctx, next) => {
    let res = ' ';
    let qutid1 = ctx.request.body.index;
    ctx.session.qutid = qutid1;
    console.log(ctx.session.qutid + "该问卷id");
    res = { code: 200, msg: '成功' };
    ctx.body = JSON.stringify(res);

}
let fillingStatus_fn = async (ctx, next) => {

    let qid = ctx.session.qutid;

    //获得问卷的问题名
    let proName = [];
    let proId = [];
    let p1 = JSON.parse(JSON.stringify(await problem.findAll({
        where: {
            questionnaireId: qid
        }
    })))
    p1.forEach(item => {
        proName.push(item.content),
        proId.push(item.id)
    })

    //根据问题的分数以及用户id
    console.log(p1.proName);

    let score1 = await score.findAll({
        where: {
            problemId: proId
        }
    })
    let s1=JSON.parse(JSON.stringify(score1))
    console.log(s1);
    let obj = {
        p1,
        s1
    }
    ctx.render('fillingStatus.html', obj)

}
module.exports = {
    '/': ['get', auth, index_fn],
    '/loginDone': ['post', loginDone_fn],
    '/registerDone': ['post', registerDone_fn],
    '/login': ['get', auth, login_fn],
    '/register': ['get', register_fn],
    '/newQuestionnaire': ['get', newQuestionnaire_fn],
    '/createQuestionnaire': ['post', createQuestionnaire_fn],
    '/questionnaire': ['get', questionnaire_fn],
    '/logout': ['post', logout_fn],
    '/information': ['get', information_fn],
    '/questionnaireDone': ['post', questionnaireDone_fn],
    '/addScoreDone': ['post', addScoreDone_fn],
    '/updatePasswordDone': ['post', updatePasswordDone_fn],
    '/updatePassword': ['get', updatePassword_fn],
    '/myQuestionnaire': ['get', myQuestionnaire_fn],
    '/myQuestionnaireDone': ['post', myQuestionnaireDone_fn],
    '/fillingStatus': ['get', fillingStatus_fn],
    '/fillingStatusDone': ['post', fillingStatusDone_fn]
    // '/addScore': ['get', addScore_fn]
}

